package cn.edu.cug.cs.gtl;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * 显示验证码的面板
 * @author sunjianhao
 */
public class SecurityCodePanel extends JPanel {
    Random random = new Random();

    /**
     * 验证码个数
     */
    static final int CODE_NUM=4;

    /**
     * 验证码
     */
    private String code = "";

    public SecurityCodePanel() {
        this.setVisible(true);
        setLayout(null);
    }

    @Override
    public void paint(Graphics g) {
        // 验证码的字母
        String wenzi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        BufferedImage image = new BufferedImage(120, 35, BufferedImage.TYPE_INT_BGR);
        Graphics graphics = image.getGraphics();
        if (!code.isEmpty()) {
            code = "";
        }
        graphics.setFont(new Font("楷体", Font.BOLD, 20));
        graphics.fillRect(0, 0, 120, 35);
        //生成四个待验证的文字
        StringBuilder stringBuilderCode=new StringBuilder();
        for (int i = 0; i < CODE_NUM; i++) {
            int index = random.nextInt(wenzi.length());
            // 截取字段
            String s = wenzi.substring(index, index + 1);
            // 验证码新增截取字段
            stringBuilderCode.append(s);
            graphics.setColor(Color.green);
            Graphics2D g2d = (Graphics2D) graphics;
            AffineTransform transform = new AffineTransform();
            // 随机转动
            transform.rotate(random.nextInt(45) * 3.14 / 180, 22 * i + 8, 7);
            // 缩放文字
            float scaleSize = random.nextFloat() + 0.8f;
            // 如果scaleSize大于1,则等于1
            if (scaleSize > 1f) {
                scaleSize = 1f;
            }
            // 进行缩放
            transform.scale(scaleSize, scaleSize);
            // 设置AffineTransform对象
            g2d.setTransform(transform);
            // 画出验证码
            graphics.drawString(s, 120 / 6 * i + 28, 35 / 2);
        }
        g.drawImage(image, 0, 0, null);
        code=stringBuilderCode.toString();
    }

    public String getCode() {
        return code;
    }

    /**
     * 更换验证码
     */
    public void changeSecurityCode(){
        repaint();
    }
}